<template>
	<ul class="list">
		<li class="item" 
			v-for="item of letters" 
			:key="item" 
			@click="handleLetterClick" 
			@touchstart="handleTouchStart"
			@touchmove="handleTouchMove"
			@touchend="handleTouchEnd"
			:ref="item"
			>{{item}}</li>
	</ul>

</template>
<script>
	export default {
		name: 'CityAlphabet',
		props: {
			cities: Object
		},
		data ( ){
			return {
				touchStatus:false,
				startY: 0,
				letterHeight: 0,
				lettersNum: 0,
				timer: null
			}
		},
		updated () { //优化，初始数据创建后就取出字母的位置和高度，方便在touch 中使用，否则每次TOUCH都要取，提高性能
 			this.startY = this.$refs['A'][0].offsetTop
 			//console.log(this.$refs['A'][0]) 这块为啥["A"]，取出来是LI A字母的元素呢
 			this.letterHeight = this.$refs['A'][0].offsetHeight
 			this.lettersNum = this.letters.length
		},
		computed: { //通过计算，把列表里字母生成数组
			letters () {
				const letters = []
				for (let i in this.cities) {
					letters.push(i)
				}
				return letters
			}
		},
		methods: {
			handleLetterClick (e){
				this.$emit("change",e.target.innerText)
			
			},
			handleTouchStart () {
				this.touchStatus= true
			},
			handleTouchMove (e) {

				if(this.touchStatus) {
					  if(this.timer){
                	clearTimeout(this.timer)
                }
                this.timer = setTimeout(() => {
                	const touchY = e.touches[0].clientY-79
					const index = Math.floor((touchY-this.startY)/this.letterHeight)
					//console.log(index)
					if(index >= 0 && index < this.lettersNum){
						this.$emit( "change" , this.letters[index])
					}
					

                })
					

				}
			},
			handleTouchEnd () {
				this.touchStatus= false
			}
		}
	}
</script>
<style lang="stylus" scoped>
@import '~styles/veribles.styl'
.list
	display:flex
	flex-direction:column
	justify-content:center
	position:absolute
	top:1.58rem
	right:0
	bottom:0
	width:.4rem
	.item
		text-align:center
		line-height:.45rem
		color:$bgColor
			
			



</style>